package cn.com.cpic.insurance.rulecheck.core;

import javax.el.ArrayELResolver;
import javax.el.BeanELResolver;
import javax.el.CompositeELResolver;
import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.FunctionMapper;
import javax.el.ListELResolver;
import javax.el.MapELResolver;
import javax.el.VariableMapper;

import org.apache.el.lang.EvaluationContext;
import org.apache.el.lang.FunctionMapperImpl;
import org.apache.el.lang.VariableMapperImpl;

/**
 * 
 * 
 * @author 代波
 * @since 2011-8-14
 */
public final class SimpleContext implements Context {
	private final BomContext bomContext;
	private final EvaluationContext evaluationContext;

	public SimpleContext(BomContext bomContext) {
		super();
		this.bomContext = bomContext;
		this.evaluationContext = buildEvaluationContext(bomContext);
	}

	public BomContext getBomContext() {
		return bomContext;
	}

	public EvaluationContext getEvaluationContext() {
		return evaluationContext;
	}

	private static EvaluationContext buildEvaluationContext(BomContext bomContext) {
		final VariableMapper varMapper = new VariableMapperImpl();
		final FunctionMapper fnMapper = new FunctionMapperImpl();
		final CompositeELResolver elResolver = new CompositeELResolver();
		elResolver.add(new BOMContextELResolver(bomContext));
		elResolver.add(new ArrayELResolver());
		elResolver.add(new ListELResolver());
		elResolver.add(new MapELResolver());
		elResolver.add(new BeanELResolver());

		ELContext context = new ELContext() {
			@Override
			public VariableMapper getVariableMapper() {
				return varMapper;
			}

			@Override
			public FunctionMapper getFunctionMapper() {
				return fnMapper;
			}

			@Override
			public ELResolver getELResolver() {
				return elResolver;
			}
		};
		return new EvaluationContext(context, fnMapper, varMapper);
	}
}
